import { useMemo, useCallback, useState } from 'react';
import { View } from '@tarojs/components';
import i18n from 'i18n-js';
import { observer } from 'mobx-react';
import Taro from '@tarojs/taro';
import { GStyleSheet } from '@/utils/DarkMode';
import { useDeviceListStore, useDeviceShare } from '@/hooks';
import FlexScrollView from '@/components/FlexScrollView';
import { isSameDevice } from '@/utils';
import deviceShareModel from '@/models/deviceShare';
import { removeReceiveShareDevices } from '@/services/share';
import Toast from '@/utils/Toast';
import DeviceItem from './components/DeviceItem';
import { ISelDevice, noRepeatAddItemToArray, deleteItemFromArray } from './models';
import BottomButtonView from './container/BottomButtonView';
import manageIcon from '../images/manage.png';
import CheckBox from '@/components/CheckBox';

const dstyles = GStyleSheet.create({
  content: {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
  },
  checkBox: {
    height: 18,
    width: 18,
    borderColor: '#A4A4A4',
  },
});

function ShareToMeDeviceList() {
  const styles = dstyles.useDynamicStyle();
  const [isEdit, setIsEdit] = useState(false);
  const [sharedDeviceSelectList, setSharedDeviceSelectList] = useState<ISelDevice[]>([]);
  const { receiveList } = useDeviceShare();
  const { data } = useDeviceListStore();
  const list: ISelDevice[] = useMemo(() => {
    const arr: ISelDevice[] = [];
    receiveList.forEach(sDevice => {
      const d = data.find(i => isSameDevice(i, sDevice));
      if (d) {
        arr.push({ ...d, isSelected: sharedDeviceSelectList.findIndex(i => isSameDevice(i, d)) > -1 });
      }
    });
    return arr;
  }, [data, receiveList, sharedDeviceSelectList]);

  const onDeviceItemPress = useCallback(
    ({ device }: { device: ISelDevice }) => {
      if (isEdit) {
        const targetSel = !device.isSelected;
        if (targetSel) {
          noRepeatAddItemToArray({ list: sharedDeviceSelectList, item: device, isSame: isSameDevice });
        } else {
          deleteItemFromArray({ list: sharedDeviceSelectList, item: device, isSame: isSameDevice });
        }
        setSharedDeviceSelectList([...sharedDeviceSelectList]);
      } else {
        Taro.navigateTo({
          url: `/pages/share/users/index?pk=${device.productKey}&mac=${device.mac}`,
        });
      }
    },
    [isEdit, sharedDeviceSelectList]
  );

  const deleteClick = useCallback(async () => {
    if (sharedDeviceSelectList && sharedDeviceSelectList.length > 0) {
      Toast.loading('');
      const res = await removeReceiveShareDevices(sharedDeviceSelectList);
      if (res.success) {
        await deviceShareModel.fetchReceiveList();
      }
      Toast.hideLoading();
    }
    setIsEdit(false);
    setSharedDeviceSelectList([]);
  }, [sharedDeviceSelectList]);

  const buttonData = useMemo(() => {
    return isEdit
      ? [{ title: i18n.t('DELETE'), onClick: deleteClick, color: 'danger', variant: 'outlined' }]
      : [{ title: i18n.t('MANAGE'), onClick: () => setIsEdit(true), icon: manageIcon }];
  }, [isEdit, deleteClick]);

  const isAllCheck = useMemo(() => {
    const currentSelect = sharedDeviceSelectList
      .sort()
      .map(item => item.deviceId)
      .join('');
    const allDevice = list
      .sort()
      .map(item => item.deviceId)
      .join('');
    return currentSelect === allDevice;
  }, [sharedDeviceSelectList, list]);

  const toggleSelect = useCallback(() => {
    if (isAllCheck) {
      setSharedDeviceSelectList([]);
    } else {
      setSharedDeviceSelectList([...list]);
    }
  }, [isAllCheck, list]);
  return (
    <View style={styles.content}>
      <View style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
        {isEdit ? (
          <View style={{ justifyContent: 'flex-end', display: 'flex', padding: '10PX 16PX 0PX 20PX' }}>
            <CheckBox style={styles.checkBox} checked={isAllCheck} onPress={toggleSelect}></CheckBox>
          </View>
        ) : null}
        <FlexScrollView id='ShareToMeDeviceList'>
          {list.map(item => (
            <DeviceItem
              key={item.deviceId}
              isSelected={item.isSelected}
              showSel={isEdit}
              device={item}
              showCount={false}
              onPress={onDeviceItemPress}
            />
          ))}
        </FlexScrollView>
      </View>
      <BottomButtonView data={buttonData} />
    </View>
  );
}

export default observer(ShareToMeDeviceList);
